package com.chengxiaoxiao.libarypartner.activity;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

import com.chengxiaoxiao.libarypartner.R;
import com.chengxiaoxiao.libarypartner.domain.ListBooksCategory;
import com.loopj.android.image.SmartImageView;

import java.util.List;
import java.util.Map;


public class MultiSelectAdapter extends BaseAdapter {

    public Map<Integer,Boolean> isCheck ;
    private List<ListBooksCategory> list;
    private Context context;

    //通过构造函数获取数据
    public MultiSelectAdapter(List<ListBooksCategory> list,Map<Integer,Boolean> isCheck, Context context) {
        this.list = list;
        this.context = context;
        this.isCheck = isCheck;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View view;
        if (convertView == null)
        {
            view = View.inflate(context, R.layout.list_item_borrow, null);
        } else
        {
            view = convertView;
        }

        SmartImageView imageIcon = (SmartImageView) view.findViewById(R.id.ivIcon);
        TextView textName = (TextView) view.findViewById(R.id.textName);
        TextView textAddress = (TextView) view.findViewById(R.id.textAddress);
        ListBooksCategory book = list.get(position);
        final CheckBox checkBox = (CheckBox)view.findViewById(R.id.checkBox);

        textName.setText(book.getBookName());
        textAddress.setText(book.getAddress());
        imageIcon.setImageUrl(book.getImagePath());

        checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isCheck.get(position)) {
                    //如果取消，则设置map集合中为false
                    checkBox.setChecked(false);

                    isCheck.put(position,false);
                } else {
                    //如果选中，则设置map集合中为true
                    checkBox.setChecked(true);
                    isCheck.put(position,true);
                }
            }
        });
        //给CheckBox设置状态,否则在复用的时候会出现状态错乱
        checkBox.setChecked(isCheck.get(position));

        return view;
    }

}
